package util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaoleilu.hutool.io.IoUtil;

import test.BitConvert;
import test.ChinaUMSZjConfig;
import test.ChinaUmsZjMessage;

public class TLVUtil {
	private static Logger logger = LoggerFactory.getLogger(TLVUtil.class);
	public  static ThreadLocal<Socket> socketPool=new ThreadLocal<Socket>(){
		
		@Override
		protected Socket initialValue() {
			try {
				return createSocket();
			} catch (IOException e) {
				logger.error("",e);
				return null;
			}
		}

		@Override
		public void remove() {
			super.remove();
			try {
				get().close();
			} catch (IOException e) {
				logger.error("",e);
			}
		}
		
	};
	private static Socket createSocket() throws IOException{
		Socket socket=new Socket();
		socket.setSoTimeout(ChinaUMSZjConfig.soTimeOut);
		socket.connect(new InetSocketAddress(ChinaUMSZjConfig.serverIp, ChinaUMSZjConfig.port),ChinaUMSZjConfig.connectTimeOut);
		return socket;
	}
	public static ChinaUmsZjMessage sendMessage(ChinaUmsZjMessage msg) throws Exception{
		Socket socket= socketPool.get();
		try {
			//获得请求报文体
			byte[] reqBody=msg.getBodyBytes();
			if(logger.isDebugEnabled()){
				logger.debug("请求报文体：{}",MacEcbUtils.bytesToHexString(reqBody));	
			}
			//计算MAC值
			byte[] key = BitConvert.Str2Hex(ChinaUMSZjConfig.chanpass);
			byte[] macByte = MacEcbUtils.getMac(key, reqBody);
			String macValue=MacEcbUtils.bytesToHexString(macByte);
			logger.debug("请求macValue：{}",macValue);
			//拼装请求报文
			byte[] req= msg.getSerialization(macValue);
			if(logger.isDebugEnabled()){
				logger.debug("请求报文：{}",MacEcbUtils.bytesToHexString(req));	
			}
			//获取请求报文长度
			int reqLength = ChinaUmsZjMessage.byteArrayToInt(ChinaUmsZjMessage.subBytes(req, 0, 2));
			logger.debug("请求报文长度：{}\t{}",reqLength,req.length);
			//发送请求报文
			IoUtil.write(socket.getOutputStream(), false, req);
			
			//获取返回报文长度
			byte[] resLength=IoUtil.readBytes(socket.getInputStream(),2);
			int len = BitConvert.byteArrayToInt(resLength);
			//获取返回报文
			byte[] res=new byte[len+2];
			System.arraycopy(resLength, 0, res, 0, 2);
			byte[] res_tmp=IoUtil.readBytes(socket.getInputStream(),len);
			System.arraycopy(res_tmp, 0, res, 2, len);
			msg.parseResponseByte(res, false);
			if(logger.isDebugEnabled()){
				logger.debug("返回报文：{}",MacEcbUtils.bytesToHexString(res));	
			}
			return msg;
		} catch (Exception e) {
			socketPool.remove();
			throw e;
		}
		
	}
}



















